//
//  UIViewController(Search).m
//
//  Created by 赵梁 on 16/3/1.
//  Copyright © 2016年 zify. All rights reserved.
//

#import "UIViewController+Search.h"

@implementation UIViewController(Search)

//这里使用递归的方式获取
- (UIViewController*)lastPresentedViewController
{
    //1.获取当前VC的下一个presentedViewController
    UIViewController *viewController = self.presentedViewController;
    if (viewController) {
        viewController = [viewController lastPresentedViewController];
    }else{
        viewController = self;
    }
    
    if ([viewController isKindOfClass:[UITabBarController class]]) {
        //2.获取当然VC是UITabBarController 就获取selectedViewController 否则返回自己
        if ([(UITabBarController *)viewController viewControllers].count>0) {
            viewController = [(UITabBarController *)viewController selectedViewController];
            return [viewController lastPresentedViewController];
        }else{
            return viewController;
        }
    }else if([viewController isKindOfClass:[UINavigationController class]]) {
        //3.获取当然VC是UINavigationController 就获取visibleViewController 否则返回自己
        if ([(UINavigationController *)viewController viewControllers].count>0) {
            viewController = [(UINavigationController *)viewController visibleViewController];
            return [viewController lastPresentedViewController];
        }else{
            return viewController;
        }
    }else{
        //3.获取当然VC不是UINavigationController或者UITabBarController，返回自己
        return viewController;
    }
}

+ (UIViewController *)rootViewController
{
    UIViewController *result;
    // Try to find the root view controller programmically
    // Find the top window (that is not an alert view or other window)
    UIWindow *topWindow = [[UIApplication sharedApplication] keyWindow];
    if (topWindow.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(topWindow in windows) {
            if (topWindow.windowLevel == UIWindowLevelNormal)
                break;
        }
    }
    
    UIView *rootView = [[topWindow subviews] objectAtIndex:0];
    id nextResponder = [rootView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]){
        result = nextResponder;
    }else if ([topWindow respondsToSelector:@selector(rootViewController)] && topWindow.rootViewController != nil){
        result = topWindow.rootViewController;
    }else {
        NSAssert(NO, @"ShareKit: Could not find a root view controller. You can assign one manually by calling [[SHK currentHelper] setRootViewController:YOURROOTVIEWCONTROLLER].");
    }
    return result;
}

+ (UIViewController*)currentViewController
{
    UIViewController *controller = [self rootViewController];
    controller = [controller lastPresentedViewController];
    return controller;
}

@end
